import { Component, EventKeyboard, Input, KeyCode, _decorator, input, } from 'cc';
const { ccclass } = _decorator;

export enum Axis {
    Horizontal = 'Horizontal',
    Vertical = 'Vertical',
}

export interface IAxisInput {
    getAxis(axisName: Axis): number;
}

@ccclass('InputWrap')
export class InputWrap extends Component implements IAxisInput {

    private _horizontalInput: number = 0;

    private _verticalInput: number = 0;

    getAxis(axisName: Axis): number {
        switch (axisName) {
            case Axis.Horizontal:
                return this._horizontalInput;
            case Axis.Vertical:
                return this._verticalInput;
        }
        return 0;
    }

    protected onLoad(): void {
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    onKeyDown(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.KEY_W:
            case KeyCode.ARROW_UP:
                this._verticalInput = 1;
                break;
            case KeyCode.KEY_A:
            case KeyCode.ARROW_LEFT:
                this._horizontalInput = -1;
                break;
            case KeyCode.KEY_S:
            case KeyCode.ARROW_DOWN:
                this._verticalInput = -1;
                break;
            case KeyCode.KEY_D:
            case KeyCode.ARROW_RIGHT:
                this._horizontalInput = 1;
                break;
        }
    }

    onKeyUp(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.KEY_W:
            case KeyCode.ARROW_UP:
                this._verticalInput = 0;
                break;
            case KeyCode.KEY_A:
            case KeyCode.ARROW_LEFT:
                this._horizontalInput = 0;
                break;
            case KeyCode.KEY_S:
            case KeyCode.ARROW_DOWN:
                this._verticalInput = 0;
                break;
            case KeyCode.KEY_D:
            case KeyCode.ARROW_RIGHT:
                this._horizontalInput = 0;
                break;
        }
    }

    protected onDestroy(): void {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

}